// let web = browser;
let web = chrome;
web.runtime.onMessage.addListener((msg) => {
  if (msg.cmd !== "cmd_get_list_item") {
    return;
  }
  document.body.style.border = "55px solid blue";
  let list = getListItems();
  web.runtime.sendMessage({
    cmd: "callback_list",
    data: list,
  });
});

function getListItems() {
  list = "";
  let nodes = document.querySelectorAll(".sitemapTree > .sitemapNode");
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i];
    processorNode(node, 0);
  }
  return list;
}
function processorNode(node, tier) {
  if (node.classList.contains("sitemapExpandableNode")) {
    let text = node.querySelector(
      ".sitemapHover > .sitemapPageLinkContainer .sitemapPageName"
    ).innerText;
    // console.log(text, "   " + tier);
    list += getSpace(tier) + "[] " + text + "\n";
    let nodes = node.querySelectorAll("ul > .sitemapNode");
    for (let i = 0; i < nodes.length; i++) {
      processorNode(nodes[i], tier + 1);
    }
  } else {
    let text = node.querySelector(".sitemapPageName").innerText;
    // console.log(text, "   " + tier);
    list += getSpace(tier) + "[] " + text + "\n";
  }
}
function getSpace(tier) {
  let space = "";
  for (let i = 0; i < tier; i++) {
    space += "  ";
  }
  return space;
}
let list = "";
let right = "25px";
let parse = function () {
  let text = document.createElement("h3");
  text.style.position = "absolute";
  text.style.top = "100px";
  text.style.backgroundColor = "white";
  text.style.padding = "10px";
  text.style.borderRadius = "10px";
  //shadow
  text.style.boxShadow = "0px 0px 10px 5px rgba(0,0,0,0.5)";
  text.style.right = right;
  text.style.zIndex = 1000;
  text.innerText = getListItems();
  text.style.display = "none";

  let button = document.createElement("button");
  button.style.position = "absolute";
  button.style.top = "50px";
  button.style.padding = "10px";
  button.style.boxShadow = "0px 0px 10px 5px rgba(0,0,0,0.5)";
  button.style.margin = "auto";
  button.style.zIndex = 1000;
  button.style.right = right;
  button.textContent = "Show/Hide";
  button.style.height = "40px";
  button.style.border = "1px solid white";
  button.style.borderRadius = "20px";
  //button padding horizontal 10px
  button.style.paddingLeft = "10px";
  button.style.paddingRight = "10px";
  button.onclick = () => {
    if (text.style.display == "none") {
      text.style.display = "block";
    } else if (text.style.display == "block") {
      text.style.display = "none";
    }
  };
  document.body.append(text);
  document.body.append(button);
  //hide text when touch screen
  document.body.addEventListener("touchstart", () => {
    if (text.style.display == "block") {
      text.style.display = "none";
    }
  });
};
let tree = document.querySelector(".sitemapTree");
if (tree) {
  setTimeout(parse, 1000);
}
